<?php

namespace App\Http\Controllers\Api;

use App\Models\Good;
use App\Models\Order;
use App\Models\User;
use http\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class PrintController extends Controller
{
    private $username = '浙江宏茂科技有限公司';
    private $secret = '966597fcf6a72d03d41ae670199442b6';

    private $dev_id = 'SW244700137';

    public $login_url = 'https://open.sw-aiot.com/api/getToken';
    public $print_url = 'https://open.sw-aiot.com/api/message/printMsg';

    public function getPrintToken()
    {

        if(Cache::get('print_token')){

            return  Cache::get('print_token');

        }else{

            $signature = $this->getSignature();
            $token  = $this->curl_post(['username'=>$this->username,'password'=>$signature[0],'times'=>$signature[1]],$this->login_url);

            if($token){
                $token = json_decode($token,true)['data']['token'];

                Cache::add('print_token',$token,110);

                return $token;
            }


        }


    }

    public function printTicket($message,$dev_id,$ptype=0,$pcopy=1){


        $data = [];
        $data['devid'] = $dev_id;
        $data['reqid'] = 88888888;
        $data['type'] = 5;
        $data['pcopy'] = $pcopy;
        $ptype && $data['ptype'] = $ptype;
        $data['vtype'] = -1;
        $data['message'] = stripslashes(json_encode($message,JSON_UNESCAPED_UNICODE));



        $res = $this->curl_post($data,$this->print_url,$this->getPrintToken());

        $res = json_decode($res,true);

        if($res && $res['code']=='401'){ //登录失效
            Cache::forget('print_token');


            $res = $this->curl_post($data,$this->print_url,$this->getPrintToken());

            $res = json_decode($res,true);
        }

        return $res;
    }

    public function getSignature(){

        $time = $this->getMilliseconds();
        $str = "secret=".$this->secret."&times=".$time."&username=".$this->username;

        $str = strtoupper(md5($str));

        return [$str,$time];
    }


    public function getMilliseconds(){

        $milliseconds = sprintf('%03d', round(microtime(true) * 1000));

        return $milliseconds;
    }




    public function curl_post($data,$url,$token=''){

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>json_encode($data,JSON_UNESCAPED_UNICODE),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'token: '.$token,
            ),
        ));
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        $response = curl_exec($curl);

        curl_close($curl);

        return $response;

    }


    public function removeEmojiChar($str)//去除字符串里的表情
    {
        $mbLen = mb_strlen($str);

        $strArr = [];
        for ($i = 0; $i < $mbLen; $i++) {
            $mbSubstr = mb_substr($str, $i, 1, 'utf-8');
            if (strlen($mbSubstr) >= 4) {
                continue;
            }
            $strArr[] = $mbSubstr;
        }

        return implode('', $strArr);

    }

    public function test(Request $request){

//        $user = User::find(166);
//        $user->name = $this->removeEmojiChar($user->nickname);
//        return $this->success($user);
        //update_pay_status(['out_trade_no'=>'2024121017272248716']);
        $order_id = $request->order_id;

        return DB::table('print_device')->value('device_code');
    }


    //打印订单标签
    public function PrintOrder($order_id){


        $order = Order::with(["goods:order_id,goods_name,goods_id,goods_price,num,total_money","user:id,name,nickname,mobile"])
            ->select(['id','user_id','money','type','old_money','check_status','order_status','pay_status','pay_time','type','check_time','created_at'])->find($order_id);



        $user = User::find($order->user_id);
        $message = [];
        $message['print'][] = ['cont'=>'兰蚌优品','type'=>'title','size'=>35];
        $dev_id = DB::table('print_device')->where('type',2)->where('cate',$order->type)->where('status',1)->value('device_code');
        if($order->type == 1){
            $message['print'][] =  ['cont'=>'开蚌(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700133';

        }elseif($order->type == 2){
            $message['print'][] =  ['cont'=>'配件(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700137';
        }else{
            $message['print'][] =  ['cont'=>'成品(客户联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
            //$dev_id = 'SW244700137';
        }
        $message['print'][] = ['type'=>'div_line'];
        $message['print'][] = ['cont'=>'下单用户 ：'.$this->removeEmojiChar($user->nickname)];
        $message['print'][] = ['cont'=>'联系电话 ：'.substr_replace($user->mobile, '****', 3, 4)];
        $message['print'][] = ['cont'=>'下单时间 ：'.$order->pay_time];
        $message['print'][] = ['cont'=>'核销时间 ：'.$order->check_time];
        $message['print'][] = ['cont'=>'商品清单','type'=>'div_line'];
        foreach ($order->goods as $k=>$v){

            $goods =  Good::with(["color:id,color","material:id,material"])
                ->where('id',$v['goods_id'])->select(['id','color_id','material_id','No',])->first();

            $message['print'][] = ['cont'=>($k+1).'.'.$v['goods_name'],'type'=>'text'];
            $message['print'][] = ['cont'=>'  '.$goods->No,'type'=>'text'];
            $message['print'][] = ['both_sides'=>['  '.$goods->color->color.'-'.$goods->material->material,$v['goods_price'].'*'.$v['num'].'  ']];

        }
        $message['print'][] = ['type'=>'div_line'];

        $money = $order->old_money?:$order->money;

        $message['print'][] = ['both_sides'=>['总计','￥ '.$money],'size'=>12];

        $message['print'][] = ['cont'=>'优惠价'.'￥ '.$order->money,'type'=>'text','size'=>12,'align'=>'right'];
        $message['print'][] = ['cont'=>'https://mp.weixin.qq.com/a/~kdAM72icbwY0dJyxiOHGug~~','type'=>'qrcode','align'=>'center','size'=>6];
        $message['print'][] = ['cont'=>'浙中首家','type'=>'text','align'=>'center','bold'=>true,'size'=>18];
        $message['print'][] = ['cont'=>'珍珠开蚌体验基地','type'=>'text','align'=>'center','bold'=>true,'size'=>15];

        $message['print'][] = ['cont'=>''];
        $message['print'][] = ['type'=>'div_line'];
        $message['print'][] = ['cont'=>''];
        $message1 = $message;

        if($order->type == 1){
            $message1['print'][1] =  ['cont'=>'开蚌(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }elseif($order->type == 2){
            $message1['print'][1] =  ['cont'=>'配件(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }else{
            $message1['print'][1] =  ['cont'=>'成品(存根联)','type'=>'text','bold'=>true,'size'=>15,'align'=>'center'];
        }

        $message1['print'] = array_slice($message1['print'], 0, -6);

        $message2 = [];

        $message2['print'] = array_merge($message['print'],$message1['print']);



        $res = $this->printTicket($message2,$dev_id);
        file_put_contents("/www/wwwroot/lanbang/pay.log",date("Y-m-d H:i:s").'-printOrder-'.json_encode($res)."\r\n",FILE_APPEND);
//        if($res['code'] == 200){
//
//            return $this->success($res);
//
//        }else{
//
//            return $this->failed('fail');
//        }



    }

}
